import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Drawer,
  Descriptions,
  Avatar,
  Tooltip,
  Row,
  Col,
  Statistic,
  Tabs,
  Switch,
  Badge,
  Divider
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
  DownloadOutlined,
  UploadOutlined,
  SettingOutlined,
  UserOutlined,
  FormOutlined,
  FileTextOutlined,
  BarChartOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import FormDesigner, { FormSchema } from '../components/FormDesigner';
import FormTemplates from '../components/FormTemplates';

interface FormItem {
  id: string;
  name: string;
  title: string;
  description?: string;
  category: string;
  status: 'draft' | 'published' | 'archived';
  schema: FormSchema;
  createdBy: string;
  createdByName: string;
  createdAt: string;
  updatedAt: string;
  submissionCount: number;
  isPublic: boolean;
  tags: string[];
}

interface FormSubmission {
  id: string;
  formId: string;
  formName: string;
  submittedBy: string;
  submittedByName: string;
  submittedAt: string;
  data: Record<string, any>;
  status: 'pending' | 'approved' | 'rejected';
  reviewedBy?: string;
  reviewedAt?: string;
  reviewComment?: string;
}

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

export default function FormManagement() {
  const [forms, setForms] = useState<FormItem[]>([]);
  const [submissions, setSubmissions] = useState<FormSubmission[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [designerVisible, setDesignerVisible] = useState(false);
  const [templatesVisible, setTemplatesVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [submissionDetailVisible, setSubmissionDetailVisible] = useState(false);
  const [selectedForm, setSelectedForm] = useState<FormItem | null>(null);
  const [selectedSubmission, setSelectedSubmission] = useState<FormSubmission | null>(null);
  const [activeTab, setActiveTab] = useState('forms');
  const [form] = Form.useForm();

  // 模拟表单数据
  const mockForms: FormItem[] = [
    {
      id: '1',
      name: 'user_registration',
      title: '用户注册表单',
      description: '新用户注册信息收集表单',
      category: '用户管理',
      status: 'published',
      schema: {
        title: '用户注册表单',
        description: '请填写以下信息完成注册',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '用户名',
            name: 'username',
            required: true,
            placeholder: '请输入用户名'
          },
          {
            id: 'field_2',
            type: 'input',
            label: '邮箱',
            name: 'email',
            required: true,
            placeholder: '请输入邮箱地址'
          }
        ]
      },
      createdBy: 'admin',
      createdByName: '系统管理员',
      createdAt: '2024-01-15T10:00:00Z',
      updatedAt: '2024-01-20T15:30:00Z',
      submissionCount: 156,
      isPublic: true,
      tags: ['注册', '用户']
    },
    {
      id: '2',
      name: 'leave_application',
      title: '请假申请表单',
      description: '员工请假申请表单',
      category: '人事管理',
      status: 'published',
      schema: {
        title: '请假申请表单',
        description: '请填写请假申请信息',
        layout: 'vertical',
        fields: [
          {
            id: 'field_1',
            type: 'input',
            label: '申请人',
            name: 'applicant',
            required: true,
            placeholder: '请输入申请人姓名'
          },
          {
            id: 'field_2',
            type: 'select',
            label: '请假类型',
            name: 'leaveType',
            required: true,
            placeholder: '请选择请假类型',
            options: [
              { label: '年假', value: 'annual' },
              { label: '病假', value: 'sick' }
            ]
          }
        ]
      },
      createdBy: 'user001',
      createdByName: '张三',
      createdAt: '2024-01-10T09:00:00Z',
      updatedAt: '2024-01-18T14:20:00Z',
      submissionCount: 89,
      isPublic: false,
      tags: ['请假', '人事']
    }
  ];

  // 模拟提交数据
  const mockSubmissions: FormSubmission[] = [
    {
      id: '1',
      formId: '1',
      formName: '用户注册表单',
      submittedBy: 'user001',
      submittedByName: '张三',
      submittedAt: '2024-01-20T10:30:00Z',
      data: {
        username: 'zhangsan',
        email: 'zhangsan@example.com'
      },
      status: 'approved'
    },
    {
      id: '2',
      formId: '2',
      formName: '请假申请表单',
      submittedBy: 'user002',
      submittedByName: '李四',
      submittedAt: '2024-01-19T14:15:00Z',
      data: {
        applicant: '李四',
        leaveType: 'annual',
        startDate: '2024-01-25',
        endDate: '2024-01-26',
        reason: '家庭事务'
      },
      status: 'pending'
    }
  ];

  useEffect(() => {
    loadForms();
    loadSubmissions();
  }, []);

  const loadForms = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setForms(mockForms);
    } catch (error) {
      message.error('加载表单失败');
    } finally {
      setLoading(false);
    }
  };

  const loadSubmissions = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300));
      setSubmissions(mockSubmissions);
    } catch (error) {
      message.error('加载提交数据失败');
    }
  };

  const handleCreate = () => {
    form.resetFields();
    setSelectedForm(null);
    setModalVisible(true);
  };

  const handleEdit = (record: FormItem) => {
    setSelectedForm(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDesign = (record: FormItem) => {
    setSelectedForm(record);
    setDesignerVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      setForms(forms.filter(f => f.id !== id));
      message.success('表单删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (selectedForm) {
        // 更新表单
        setForms(forms.map(f => f.id === selectedForm.id ? { ...f, ...values } : f));
        message.success('表单更新成功');
      } else {
        // 创建表单
        const newForm: FormItem = {
          id: Date.now().toString(),
          ...values,
          schema: {
            title: values.title,
            description: values.description,
            layout: 'vertical',
            fields: []
          },
          createdBy: 'current_user',
          createdByName: '当前用户',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          submissionCount: 0,
          tags: []
        };
        setForms([...forms, newForm]);
        message.success('表单创建成功');
      }
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleFormSave = (schema: FormSchema) => {
    if (selectedForm) {
      setForms(forms.map(f => 
        f.id === selectedForm.id 
          ? { ...f, schema, updatedAt: new Date().toISOString() }
          : f
      ));
      message.success('表单设计保存成功');
    }
  };

  const handleUseTemplate = (template: any) => {
    const newForm: FormItem = {
      id: Date.now().toString(),
      name: template.name.toLowerCase().replace(/\s+/g, '_'),
      title: template.name,
      description: template.description,
      category: template.category,
      status: 'draft',
      schema: template.schema,
      createdBy: 'current_user',
      createdByName: '当前用户',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      submissionCount: 0,
      isPublic: false,
      tags: template.tags
    };
    setForms([...forms, newForm]);
    setTemplatesVisible(false);
    message.success(`已从模板创建表单：${template.name}`);
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      draft: 'orange',
      published: 'green',
      archived: 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      draft: '草稿',
      published: '已发布',
      archived: '已归档'
    };
    return texts[status] || status;
  };

  const getSubmissionStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      pending: 'orange',
      approved: 'green',
      rejected: 'red'
    };
    return colors[status] || 'default';
  };

  const getSubmissionStatusText = (status: string) => {
    const texts: Record<string, string> = {
      pending: '待审核',
      approved: '已通过',
      rejected: '已拒绝'
    };
    return texts[status] || status;
  };

  const formColumns: ColumnsType<FormItem> = [
    {
      title: '表单名称',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.name}</div>
        </div>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (text) => <Tag>{text}</Tag>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '提交数',
      dataIndex: 'submissionCount',
      key: 'submissionCount',
      render: (count) => <Badge count={count} showZero />
    },
    {
      title: '创建人',
      dataIndex: 'createdByName',
      key: 'createdByName',
      render: (name) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Avatar size={20} icon={<UserOutlined />} />
          {name}
        </div>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedForm(record);
                setDetailVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="设计表单">
            <Button
              type="text"
              icon={<FormOutlined />}
              onClick={() => handleDesign(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="text"
              icon={<CopyOutlined />}
              onClick={() => {
                const newForm = {
                  ...record,
                  id: Date.now().toString(),
                  name: record.name + '_copy',
                  title: record.title + ' (副本)',
                  status: 'draft' as const,
                  createdAt: new Date().toISOString(),
                  submissionCount: 0
                };
                setForms([...forms, newForm]);
                message.success('表单复制成功');
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定删除这个表单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                icon={<DeleteOutlined />}
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  const submissionColumns: ColumnsType<FormSubmission> = [
    {
      title: '表单名称',
      dataIndex: 'formName',
      key: 'formName'
    },
    {
      title: '提交人',
      dataIndex: 'submittedByName',
      key: 'submittedByName',
      render: (name) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Avatar size={20} icon={<UserOutlined />} />
          {name}
        </div>
      )
    },
    {
      title: '提交时间',
      dataIndex: 'submittedAt',
      key: 'submittedAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getSubmissionStatusColor(status)}>
          {getSubmissionStatusText(status)}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedSubmission(record);
              setSubmissionDetailVisible(true);
            }}
          >
            查看
          </Button>
          {record.status === 'pending' && (
            <>
              <Button
                type="text"
                style={{ color: 'green' }}
                onClick={() => {
                  setSubmissions(submissions.map(s => 
                    s.id === record.id ? { ...s, status: 'approved' } : s
                  ));
                  message.success('已通过审核');
                }}
              >
                通过
              </Button>
              <Button
                type="text"
                danger
                onClick={() => {
                  setSubmissions(submissions.map(s => 
                    s.id === record.id ? { ...s, status: 'rejected' } : s
                  ));
                  message.success('已拒绝');
                }}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和统计 */}
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ margin: 0, marginBottom: 16 }}>表单管理</h2>
        <Row gutter={16}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总表单数"
                value={forms.length}
                prefix={<FormOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已发布"
                value={forms.filter(f => f.status === 'published').length}
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总提交数"
                value={forms.reduce((sum, f) => sum + f.submissionCount, 0)}
                prefix={<FileTextOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="待审核"
                value={submissions.filter(s => s.status === 'pending').length}
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
        </Row>
      </div>

      {/* 主要内容 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="表单列表" key="forms">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
                  新建表单
                </Button>
                <Button icon={<FileTextOutlined />} onClick={() => setTemplatesVisible(true)}>
                  表单模板
                </Button>
                <Button icon={<UploadOutlined />}>
                  导入表单
                </Button>
                <Button icon={<ReloadOutlined />} onClick={loadForms}>
                  刷新
                </Button>
              </Space>
            </div>
            
            <Table
              columns={formColumns}
              dataSource={forms}
              rowKey="id"
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          </TabPane>
          
          <TabPane tab="提交数据" key="submissions">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button icon={<DownloadOutlined />}>
                  导出数据
                </Button>
                <Button icon={<BarChartOutlined />}>
                  数据统计
                </Button>
                <Button icon={<ReloadOutlined />} onClick={loadSubmissions}>
                  刷新
                </Button>
              </Space>
            </div>
            
            <Table
              columns={submissionColumns}
              dataSource={submissions}
              rowKey="id"
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 创建/编辑表单模态框 */}
      <Modal
        title={selectedForm ? '编辑表单' : '新建表单'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="表单标题"
            name="title"
            rules={[{ required: true, message: '请输入表单标题' }]}
          >
            <Input placeholder="请输入表单标题" />
          </Form.Item>
          
          <Form.Item
            label="表单名称"
            name="name"
            rules={[{ required: true, message: '请输入表单名称' }]}
          >
            <Input placeholder="请输入表单名称（英文，用于API调用）" />
          </Form.Item>
          
          <Form.Item label="表单描述" name="description">
            <TextArea rows={3} placeholder="请输入表单描述" />
          </Form.Item>
          
          <Form.Item
            label="分类"
            name="category"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              <Option value="用户管理">用户管理</Option>
              <Option value="人事管理">人事管理</Option>
              <Option value="客户服务">客户服务</Option>
              <Option value="活动管理">活动管理</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="draft">草稿</Option>
              <Option value="published">已发布</Option>
              <Option value="archived">已归档</Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="是否公开" name="isPublic" valuePropName="checked">
            <Switch />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {selectedForm ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 表单设计器抽屉 */}
      <Drawer
        title={`设计表单 - ${selectedForm?.title}`}
        placement="right"
        width="90%"
        open={designerVisible}
        onClose={() => setDesignerVisible(false)}
        destroyOnClose
      >
        {selectedForm && (
          <FormDesigner
            initialSchema={selectedForm.schema}
            onSave={handleFormSave}
          />
        )}
      </Drawer>

      {/* 表单模板抽屉 */}
      <Drawer
        title="表单模板"
        placement="right"
        width="80%"
        open={templatesVisible}
        onClose={() => setTemplatesVisible(false)}
      >
        <FormTemplates
          onCreateFromTemplate={handleUseTemplate}
        />
      </Drawer>

      {/* 表单详情抽屉 */}
      <Drawer
        title="表单详情"
        placement="right"
        width={600}
        open={detailVisible}
        onClose={() => setDetailVisible(false)}
      >
        {selectedForm && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="表单标题">{selectedForm.title}</Descriptions.Item>
              <Descriptions.Item label="表单名称">{selectedForm.name}</Descriptions.Item>
              <Descriptions.Item label="描述">{selectedForm.description}</Descriptions.Item>
              <Descriptions.Item label="分类">{selectedForm.category}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getStatusColor(selectedForm.status)}>
                  {getStatusText(selectedForm.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="提交数">{selectedForm.submissionCount}</Descriptions.Item>
              <Descriptions.Item label="创建人">{selectedForm.createdByName}</Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {dayjs(selectedForm.createdAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {dayjs(selectedForm.updatedAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="字段数量">{selectedForm.schema.fields.length}</Descriptions.Item>
            </Descriptions>
            
            <Divider>字段列表</Divider>
            <div style={{ maxHeight: 300, overflowY: 'auto' }}>
              {selectedForm.schema.fields.map((field, index) => (
                <div key={field.id} style={{ 
                  padding: '8px 12px', 
                  border: '1px solid #f0f0f0', 
                  borderRadius: 4, 
                  marginBottom: 4
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <strong>{field.label}</strong>
                      {field.required && <span style={{ color: 'red', marginLeft: 4 }}>*</span>}
                      <div style={{ fontSize: 12, color: '#666' }}>
                        {field.type} | {field.name}
                      </div>
                    </div>
                    <Tag>{field.type}</Tag>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </Drawer>

      {/* 提交详情抽屉 */}
      <Drawer
        title="提交详情"
        placement="right"
        width={600}
        open={submissionDetailVisible}
        onClose={() => setSubmissionDetailVisible(false)}
      >
        {selectedSubmission && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="表单名称">{selectedSubmission.formName}</Descriptions.Item>
              <Descriptions.Item label="提交人">{selectedSubmission.submittedByName}</Descriptions.Item>
              <Descriptions.Item label="提交时间">
                {dayjs(selectedSubmission.submittedAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getSubmissionStatusColor(selectedSubmission.status)}>
                  {getSubmissionStatusText(selectedSubmission.status)}
                </Tag>
              </Descriptions.Item>
            </Descriptions>
            
            <Divider>提交数据</Divider>
            <div style={{ background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
              <pre style={{ margin: 0, fontSize: 12 }}>
                {JSON.stringify(selectedSubmission.data, null, 2)}
              </pre>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}